var pageCode = null, manuBatchCode = null, facilitiesCode = null, orgId = null;
var pageSet = {};
var sgdText = "生产工单";
var processStatus = "CREATE";
var pageAutoWork = true;
var fileId = null;

$(function() {
	pageCode = request("code");
	orgId = request("orgId");
	$("#code").focus();
	$("#code").keyup(function(e) {
		if(e.which == 13) {
			searchOrderInfo(this.value);
		}
	});
	if (!pageCode) {
		alert("未搜索到传入的页面编码，请联系管理员！");
		return;
	}

	$.post(host + "dataCollection/getDataCollectionPage", {code: pageCode}, function(res) {
		if (res.result) {
			pageSet = res.data;

            if (pageSet.scanFacilities) {
                $("#facInputPanel").show();

                $("#facCode").keypress(function(e) {
                    if(e.which == 13) {
                        getFacilitiesInfo(this.value);
                    }
                });
            }
            if (pageSet.scanUser) {
                $("#userCodePanel").show();
            }
            var detailHtml = pageSet.batchInfo;
            if (detailHtml) {
                for (var name in {}) {
                    detailHtml = detailHtml.replace('{' + name + '}', res[name]);
                }
                detailHtml = detailHtml.replace(/\{(.*?)\}/g, '&nbsp;&nbsp;&nbsp;&nbsp;');

                $("#orderInfo").html(detailHtml);
                $("#orderInfoPanel").show();
            } else {
                $("#orderInfo").html('订单信息');
                $("#orderInfoPanel").hide();
            }
            if (res.Dc_Btn_List.length > 0) {
                showDataTab(res.Dc_Btn_List);
            }
            layui.use(["form", "layer"], function() {
                var form = layui.form;
                layer = layui.layer;

                form.on("switch(autoWork)", function(data) {
                    //开关是否开启，true或者false
                    pageAutoWork = data.elem.checked;
				});
            });
		} else {
			alert(res.msg);
		}
	}, "json");
});
function showDataTab(list) {
	var tables = {};
    for (var i = 0;i < list.length;i ++) {
    	$("#data_tab_title").append('<li role="tab" aria-controls="tab_' + list[i].id + '" id="ti_' + list[i].id + '">' + list[i].name + '</li>');
        $("#data_tab").append('<div id="tab_' + list[i].id + '"><table id="tb_' + list[i].id + '"></table></div>');

		if (list[i].columns) {
			var columns = list[i].columns;
			var cols = [{type: 'numbers'}];
			for (var j = 0;j < columns.length;j ++) {
                cols.push({title: columns[j].NAME, field: columns[j].COLUMN_NAME.toUpperCase(), width: columns[j].WIDTH ? columns[j].WIDTH : 100, minWidth: 60});
			}
            tables[list[i].id] = cols;
		}
    }

    layui.use(['table', 'element'], function() {
        var table = layui.table;
        var element = layui.element;

		for (var id in tables) {
			table.render({
				elem: '#tb_' + id,
				loading: true,
				even: true,
				cols: [
					tables[id]
				],
				method: "post",
				url: host + "dataCollection/getHistoryList?id=" + id + "&pageCode=" + pageCode,
				page: true, //是否显示分页
				limits: [12, 20, 50],
				limit: 12,//每页默认显示的数量
				done: function(res, curr, count) {
					//layuiRowspan(['CODE', 'PRODUCTNAME'], 1);//支持数组
				}
			});
        }
    });
}
function scanRfidQuery() {
    searchOrderInfo($("#code").val());
}
var orderCode = null, manuBatchInfo = null;
var facCode = null, facOriNumber = null;
function searchOrderInfo(code) {
	$.post(host + 'dataCollection/searchOrderInfo', {code: code, pageCode: pageCode}, function(res) {
		if (res.result) {
			manuBatchInfo = res;
			orderCode = code;
            fileId = res.fileId;
			if (fileId) {
				$("#sopBtnDiy").show();
                openSop();
			} else {
                $("#sopBtnDiy").hide();
			}

			var detailHtml = pageSet.batchInfo;
			if (detailHtml) {
                for (var name in res) {
                    detailHtml = detailHtml.replace('{' + 	name + '}', res[name]);
                }
                $("#orderInfo").html(detailHtml);
                $("#orderInfoPanel").show();
			} else {
                $("#orderInfo").html('订单信息');
                $("#orderInfoPanel").hide();
			}
            processStatus = res.STATUS;
			if (processStatus == 'START') {
				$("#startBtn").hide();
                $("#finishBtn").show();
			}

			if(processStatus != 'STOP'){
				$().hide();
			}

			if (pageAutoWork) {
                submitData('true');
			}
		} else {
			alert(res.msg);
		}
	}, "json");
}
function getFacilitiesInfo(code) {
	$.post(host + 'dataCollection/getFacilitiesInfo', {code: code}, function(res) {
		if (res.result) {
			facCode = code;
			facOriNumber = res.ORI_NUMBER;
			var text = nvl(res.NAME, '') + (res.ORI_NUMBER ? "\r\n型号：" + res.ORI_NUMBER : "");
            $("#facInfoPanel").show();
			$("#facInfo").html(text);
		} else {
			alert(res.msg);
		}
	}, "json");
}
var subbool = false;
function submitData(rework) {
	if (!orderCode) {
		alert(sgdText + "号不规范！");
		return;
	}
    var userCode = $("#userCode").val();
    if (pageSet.scanUser && !userCode) {
        alert("请先扫描工号！");
        return;
    }
	var fCode = $("#facCode").val();
	if (pageSet.scanFacilities && !fCode) {
		alert("设备编码不能为空！");
		return;
	}
	if (subbool) {
		return;
	}
	subbool = true;
	$.post(host + 'dataCollection/saveJobOrderInfo', {
            orderCode: orderCode,
			facCode: fCode,
			description: $("#description").val(),
			pageCode: pageCode,
			isRework: rework,
            userCode: userCode,
			status: processStatus
		},
		function(res) {
			subbool = false;
			if (res.msg == "rework") {
				if (window.confirm("“" + pageSet.name + "” 工序之前已执行，是否再次执行“" + pageSet.name + "”工序？")) {
					submitData('true');
				}
				return;
            } else {
                alert(res.msg);
            }
			if (res.result) {// && pageSet.isRefresh
                $("#userCode")[0].select();
                if (processStatus == 'START') {
                    processStatus = "OK";
                    $("#finishBtn").hide();
                } else if (processStatus == 'CREATE') {
                    processStatus = "START";
                    $("#startBtn").hide();
                    $("#finishBtn").show();
				}
				//window.location.reload();
			}
	}, "json");
}
function refresh() {
	window.location.reload();
}
//保存数采的数据
function saveDCData(pageId) {
	var data = null;
	$.each(vm.hisDataList,function(i,v) {
		if(v.PAGEID == pageId) {
            data = v.DATA;
		}
	});
	if(data == null) {
        alert("数据为空，请检查！");
        return;
	}
    $.post(host + 'dataCollection/saveDCData',
        {pageId:pageId,data:JSON.stringify(data)},
        function(res) {
    	alert(res.msg);
	}, "json");
}
$(function() {
    $("img").each(function() {
        if (this.outerHTML.indexOf("scanbutton") > -1) {
            $(this).hide();
        }
    })
});
//打开工艺作业指导书
function openSop() {
	if (fileId) {
        top.layer.open({
            type: 2,
            title: "作业指导书",
            shadeClose: true,
            shade: 0.6,
            area: ['80%', '80%'],
            fixed:true,
            content: host + 'file?id=' + fileId,
            end:function(){
            }
        });
	}
}